from utlis.smscode import sms_code
import re,random
from utlis.mysql import db
#开启debug模式
settings = {'debug' : True}
# 配置跨域
from utlis.CORS import BaseHandler
from utlis.instrument import pomition
# 获取全部   roles   表

class MainHandler(BaseHandler):
    def get(self):
       sql="""select * from roles;"""
       res=db.findAll(sql)
       list=[]
       for i in res:
           list.append({
               "id":i["id"],
               "name":i["name"]
           })
       self.finish({"code":200,'msg':list})

# 穿梭框
class Rbac(BaseHandler):
    def get(self):
        # 获取参数 所有资源
        roleid = self.get_query_argument("roleid")
        # 所有资源
        sql = "select * from resource where pid>0"
        res = db.findAll(sql)
        data = [{"key": i['id'], 'label': i['name']} for i in res]
        # 此角色选择的资源
        sql1 = "select resourceid from role_resource where userid=%d" % (int(roleid))
        idlist = db.findAll(sql1)
        checklist = []
        for j in idlist:
            checklist.append(j['resourceid'])
        mes = {"code": 200, 'reslist': data, 'checklist': checklist}
        self.write(mes)

# 权限配置
import json
class pzrbac(BaseHandler):
    def post(self):
        data=self.request.body
        print("body>>>>>>>>",data)
        mes=json.loads(data)
        userid=mes["userid"]
        resourceid=mes["resourceid"]
        sql1=f"""delete from role_resource where userid = {userid};"""
        db.add(sql1)
        db.commit()
        for i in resourceid:
            sql2=f"""insert into role_resource(userid,resourceid) values ({userid},{i});"""
            db.add(sql2)
            db.commit()
        self.finish({"code":200,'msg':'添加成功'})

# 给用户更换角色
class upjue(BaseHandler):
    def post(self):
        data=self.request.body
        mes=json.loads(data)
        usrname=mes["username"]
        rid=mes["rid"]
        print(rid)
        print(usrname)
        sql=f"""update admin_user set roleid={int(rid)} where username='{usrname}';"""
        db.add(sql)
        db.commit()
        self.finish({"code":200,'msg':'修改成功'})

# 展示所有用户
class getuser(BaseHandler):
    def get(self):
        sql="""select admin_user.name,username,roles.name as pname from admin_user,roles where admin_user.roleid=roles.id;"""
        res=db.findAll(sql)
        self.finish({"code":200,'msg':res})


# 展示所有角色
class getroles(BaseHandler):
    def get(self):
        sql = """select * from roles;"""
        res = db.findAll(sql)
        self.finish({"code": 200, 'msg': res})



# 图片验证码，未完工




from utlis.commit import md5,prepare
def post(self):
    # 管理员设置密码统一标准
    password="123456"
    # 登录时如果密码是初始密码，强制修改密码页面，其他页面不能操作 beforEach
    pwd=md5(password)
    mes={"code":1,"pwd":pwd}
    self.write(mes)

# 登录视图
import time
from utlis.my_jwt import jj
from myredis import r
class Login(BaseHandler):
    def post(self):
        data=self.request.body
        mes=json.loads(data)
        username=mes["username"]
        password=mes["password"]
        jiamipwd=md5(password)
        print("jiamipwd>>>>>>>>>>>>",jiamipwd)
        print("username>>>>>>>>>>>>",username)
        print("password>>>>>>>>>>>>",password)
        if not all([username,password]):
            self.finish({"code":400,"msg":"字段不完整"})
            return
        sql=f""" select * from admin_user where username="{username}";"""
        res=db.findone(sql)
        print("res>>>>>>>",res)
        if not res:
            self.finish({"code":1011,'msg':'用户不存在'})
            return
        if res["password"]!=jiamipwd:
            self.finish({"code":1022,'msg':"密码错误"})
            return
        print("roleid>>>>>>>>>>",res["roleid"])



        sql2 = f"""select re.*,pre.name as pname from role_resource as rr left join resource as re on rr.resourceid=re.id left join resource as pre on pre.id = re.pid where rr.userid={res["roleid"]}"""
        ress = db.findAll(sql2)
        list = []
        menulist = []
        urllist=[]
        url=[]
        for i in ress:
            if i['pid'] not in menulist:
                urllist.append(i['url'])
                list.append({'id': i['pid'], 'name': i['pname'], 'son': []})
                menulist.append(i['pid'])
        for j in ress:
            for index, p in enumerate(list):
                if j['pid'] == p['id']:
                    list[index]['son'].append({'id': j['id'], 'name': j['name'], 'url': j['url']})








        # 生成token
        datas={"data":{
            "name":res["username"],
            "userid":res["id"],
            "exp":time.time(),
            "roleid":res['roleid']
        }}
        token=jj.jwt_encode(datas)
        url=prepare(res["roleid"])
        key = "interlist" + str(res['roleid'])
        r.set_str(key, json.dumps(url))
        self.finish({"code":200,
                     'msg':"登陆成功",
                     'token':token,
                     'menulist':list,
                     'state':res["state"],
                     'uid':res["id"],
                     'urllist':urllist,
                     'url':url
                     })

class adduser(BaseHandler):
    def post(self):
        data=self.request.body
        mes=json.loads(data)
        name=mes["name"]
        username=mes["username"]
        pwd=mes["pwd"]
        rid=mes["value"]
        jiapwd=md5(pwd)
        sqll=f"""select * from p2p.admin_user where username="{username}";"""
        res=db.findone(sqll)
        if res:
            self.finish({"code":400,'msg':"账号重复"})
        else:
            sql="insert into p2p.admin_user(name, username, password, roleid,state) values('%s','%s','%s',%d,%d)"%(name,username,jiapwd,rid,0)
            db.add(sql)
            db.commit()
            self.finish({"code":200,'msg':'添加成功'})

class addrole(BaseHandler):
    def post(self):
        data=self.request.body
        res=json.loads(data)
        name=res["name"]
        print("name>>>>>>>>>>", name)
        if name:
            sql1=f"""select * from p2p.roles where name="{name}";"""""
            res=db.findone(sql1)
            print(res,">>>>>>>>")
            if res!=None:
                self.finish({"code":400,'msg':'用户名重复'})
            else:
                print("name>>>>>>>>>>",name)
                sql2=f"""insert into p2p.roles(name) values ("{name}");"""
                db.add(sql2)
                db.commit()
                self.finish({"code":200,'msg':"添加成功"})
        else:
            self.finish({"code":400,'msg':"请输入内容"})

class uppwd(BaseHandler):
    def post(self):
         datas=self.request.body
         data=json.loads(datas)
         pwd=data["password"]
         userid=data["userid"]
         if not all([pwd,userid]):
             self.finish({"code":400,'msg':'请输入数据'})
         spwd=md5(pwd)
         sql=f"""update admin_user set password="{spwd}",state=1 where id={int(userid)}"""
         db.add(sql)
         db.commit()
         self.finish({"code":200,'msg':'修改成功'})

class quit_port(BaseHandler):
    def post(self):
        # 从前端获取token
        headers = self.request.headers
        token = headers['token']
        # 拼接键
        key="logoutlist"
        r.sortedset_add(key,token,int(time.time()))
        self.finish({"code":200,'msg':"删除成功"})
